<template>
  <PageLayout full :pageStyle="pageStyle">
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('ShareManage.NavigateTitle.Text') }}</view>
      </HeaderLayout>
    </template>
    <view class="share-manage">
      <view class="no-content" v-if="shareList.length === 0">
        <view class="no-content-des">{{ $t('ShareManage.NoShareOtherDataDes.Text') }}</view>
        <view class="btn">
          <ActionButton @click="shareOther"> + {{ $t('ShareManage.AddShare.Text') }} </ActionButton>
        </view>
      </view>
      <view class="have-content" v-else>
        <view class="share-title">{{ $t('ShareManage.AlreadySharedGive.Text') }}：</view>
        <view class="share-list-box">
          <view class="share-box" v-for="(item, index) in shareList" :key="index">
            <view class="user-name">{{ item.guestId.replace('+86', '') }}</view>
            <view class="user-remove" @click="showRemoveUser(item, index)">{{
              $t('ShareManage.RemoveUser.Text')
            }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 请勿删除分享图片的cavans -->
    <canvas
      canvas-id="share-canvas"
      style="position: absolute; top: -1000px; left: -1000px; width: 225px; height: 180px"
    ></canvas>

    <template #footer v-if="shareList.length !== 0">
      <FooterLayout v-if="shareList.length !== 0" fixed :size="footerSize" :footer-style="footerStyle">
        <ActionButton @click="shareOther"> + {{ $t('ShareManage.AddShare.Text') }} </ActionButton>
      </FooterLayout>
    </template>
  </PageLayout>
  <!-- 移除用户弹窗 -->
  <Modal
    :visible="removeUserPop"
    :title="$t('APP.Common.Tips.Text')"
    :cancel-text="$t('APP.Common.Cancel.Text')"
    :ok-text="$t('APP.Common.Confirm.Text')"
    @ok="confirmRemoveUser"
    @cancel="cancelRemove"
  >
    <text>{{ $t('ShareAppliance.RemoveShareUserTips.Text') }}</text>
  </Modal>
  <!-- 分享用户提示框 -->
  <Modal
    :visible="shareShowPop"
    :title="$t('APP.Common.Tips.Text')"
    :description="$t('GotoShare.shareNoticeTips.Text')"
    :cancel-text="$t('APP.Common.Cancel.Text')"
    :ok-text="$t('APP.Common.Confirm.Text')"
    open-type="share"
    @ok="confirmShare"
    @cancel="cancelShare"
  />
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import Modal from '@/common/modal.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'
import FooterLayout from '@/layout/page/footer.vue'

import { footerStyle, footerSize } from '@/layout/appliance/style'
// 请勿将onShareAppMessage删除
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
import { removeShareApp } from '@/api/appliance'
import { getApplianceShareUserList, type ApplianceShareUserType } from '@/api/wxuserSignInfo'
import { useI18n } from 'vue-i18n'
import { actionDebounce, loadShareToken } from '@/utils/mpHelper'
import { useAccountStore } from '@/store/account'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { useHeaderBarShare } from '@/utils/composition/useShare'

const i18n = useI18n()
const accountStore = useAccountStore()

const pageStyle = {
  backgroundColor: '#f4f4f4',
}
const headerStyle = {
  backgroundColor: '#fff',
}

const haId = ref('')
const type = ref('')
const name = ref('')
const vib = ref('')

const shareList = ref<ApplianceShareUserType[]>([])
const currentShareUser = ref<ApplianceShareUserType | null>(null)
const removeUserPop = ref(false)
const currentIndex = ref(0)
const removeUserName = ref('')
const removeUserAppliance = ref('')
const shareShowPop = ref(false)

onLoad((query) => {
  haId.value = query?.haId
  type.value = query?.type
  name.value = decodeURIComponent(query?.name)
  vib.value = query?.vib
  iniData()
})

/**
 * 分享家电
 */
useHeaderBarShare({
  vib,
  name,
  type,
})

/**
 * 获取分享的用户数据
 */
async function iniData() {
  try {
    const res = await getApplianceShareUserList(haId.value)
    const temShareList = res.data.share || []
    temShareList.forEach((item: ApplianceShareUserType) => {
      if (item.haid == haId.value) {
        shareList.value.push(item)
      }
    })
  } catch (error) {
    console.error('获取分享用户数据失败', error)
  }
}
/**
 * 移除被分享的用户
 */
function showRemoveUser(item: ApplianceShareUserType, index: number) {
  removeUserPop.value = true
  currentShareUser.value = item
  currentIndex.value = index
  removeUserName.value = item.tname == null ? item.guestId : item.tname
  removeUserAppliance.value = item.haName
}
async function confirmRemoveUser() {
  uni.showLoading({
    title: i18n.t('APP.Common.Deleting.Text'),
  })
  try {
    if (currentShareUser.value) {
      trackEvent('remove_share', {}, TrackType.ApplianceDetail, 'Appliance.ShareManager.RemoveShare.Appliance')
      await removeShareApp(currentShareUser.value.haid, currentShareUser.value.guestId)
      trackEvent('ShareManage.RemoveUser.Text', {}, TrackType.ApplianceDetail)
      shareList.value.splice(currentIndex.value, 1)
      removeUserPop.value = false
    }
    uni.hideLoading()
  } catch (error) {
    uni.hideLoading()
  }
}
function cancelRemove() {
  removeUserPop.value = false
}
const shareOther = actionDebounce({
  call: async () => {
    await loadShareToken(haId.value, type.value)
    if (accountStore.sharetoken) {
      shareShowPop.value = true
    } else {
      uni.showToast({
        title: '获取shareToken失败',
        icon: 'error',
        duration: 3000,
      })
    }
  },
})

function confirmShare() {
  shareShowPop.value = false
  trackEvent('share_appliance', {}, TrackType.ApplianceDetail, 'Appliance.ShareManager.Share.Appliance')
}
function cancelShare() {
  shareShowPop.value = false
}
</script>

<style scoped lang="less">
.share-manage {
  width: 100%;
  height: 100%;
  font-family: 'PingFang SC';
  font-style: normal;
  position: relative;
  overflow: hidden;

  .no-content {
    width: 100%;
    height: 220rpx;
    margin-top: 70%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    .no-content-des {
      font-weight: 400;
      font-size: 32rpx;
      color: var(--dark-color);
      opacity: 0.6;
    }
  }
  .have-content {
    .share-title {
      height: 80rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: var(--dark-color);
      opacity: 0.6;
      padding: 24rpx 0 16rpx 32rpx;
      box-sizing: border-box;
    }
    .share-list-box {
      background-color: #fff;
      padding-left: 32rpx;
      .share-box {
        padding-right: 32rpx;
        height: 112rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1rpx solid #e2e2e2;
        .user-name {
          font-weight: 500;
          font-size: 32rpx;
          color: var(--dark-color);
          opacity: 0.9;
        }
        .user-remove {
          font-weight: 400;
          font-size: 32rpx;
          color: var(--primary-color);
        }
      }
    }
  }
  .btn {
    width: calc(100% - 32rpx);
    padding: 0 32rpx;
  }
}
</style>
